package com.example.replacebooks.service;

import cn.hutool.core.date.DateUtil;
import com.example.replacebooks.common.JwtTokenUtils;
import com.example.replacebooks.entity.Bookinfo;
import com.example.replacebooks.entity.Orders;
import com.example.replacebooks.entity.Params;
import com.example.replacebooks.entity.User;
import com.example.replacebooks.mapper.BookinfoMapper;
import com.example.replacebooks.mapper.OrderMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private BookinfoMapper bookinfoMapper;

    public List<Orders> findAll(){
        return orderMapper.selectAll();
    }

    public PageInfo<Orders> findBySearch(Params params){
        User currentUser = JwtTokenUtils.getCurrentUser();
        Integer userid = currentUser.getUserid();
        Integer role = currentUser.getRole();
        // 开启分页查询
        PageHelper.startPage(params.getPageNum(),params.getPageSize());
        // 接下来的查询会自动按照当前开启的分页查询
        List<Orders> list = orderMapper.findBySearch(params, userid, role);
        return PageInfo.of(list);
    }

    public void add(Orders orders) {
        //  进行重复性判断，同一id的地址替换，不同id新增
        Orders orderid = orderMapper.findByOrderid(orders.getOrderid());
        if (orderid != null){
            // 该id已存在
            orderMapper.updateByOrderid(orders);
        }else{
            orders.setCreatetime(DateUtil.now());
            orderMapper.insertSelective(orders);
        }
    }

    public void addcart(Orders orders) {
        Bookinfo list = bookinfoMapper.findByBookid(orders.getBookid());
        orders.setPrice(list.getPrice());
        orderMapper.insertSelective(orders);
    }

    public void UpdateByOrderid(Orders orders) {
        orderMapper.updateByOrderid(orders);
    }

    public void delete(Integer orderid) {
        orderMapper.deleteByPrimaryKey(orderid);
    }

    public Orders findByBookidAndUserid(Integer bookid, Integer userid) {
        Orders orders = orderMapper.findByBookidAndUserid(bookid, userid);
        return orders;
    }
}
